package week7;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 36. 有效的数独
 * https://leetcode-cn.com/problems/valid-sudoku/
 *
 * 执行结果：  通过  显示详情
 *
 * 添加备注
 * 执行用时：2 ms, 在所有 Java 提交中击败了71.09% 的用户
 * 内存消耗：38.2 MB, 在所有 Java 提交中击败了89.13% 的用户
 * 通过测试用例：507 / 507
 * 炫耀一下:
 *
 *
 */
public class Week7ValidSudoku {

    public boolean isValidSudoku(char[][] board) {
        boolean valid = false;
        if(board.length == 9 && board[0].length == 9) {
            HashMap<Integer, Integer>[] rowMapArray = new HashMap[9];
            HashMap<Integer, Integer>[] columnMapArray = new HashMap[9];
            HashMap<Integer, Integer>[] boxMapArray = new HashMap[9];

            for(int size = 0; size < 9; size++) {
                rowMapArray[size] = new HashMap<Integer, Integer>();
                columnMapArray[size] = new HashMap<Integer, Integer>();
                boxMapArray[size] = new HashMap<Integer, Integer>();
            }

            // 验证 数独
            for(int rowSize = 0; rowSize < 9; rowSize++) {
                for(int columnSize = 0; columnSize < 9; columnSize++) {
                    char cellValue = board[rowSize][columnSize];
                    if(cellValue != '.') {
                        int num = (int)cellValue;
                        int boxIndex = (rowSize / 3) * 3 + columnSize / 3;

                        // 处理当前值
                        int rowValue = rowMapArray[rowSize].getOrDefault(num, 0);
                        int columnValue = columnMapArray[columnSize].getOrDefault(num, 0);
                        int boxValue = boxMapArray[boxIndex].getOrDefault(num, 0);


                        // 检查数值是否出现
                        if(rowValue <= 0 && columnValue <= 0 && boxValue <= 0) {
                            rowMapArray[rowSize].put(num, rowValue + 1 );
                            columnMapArray[columnSize].put(num, columnValue + 1);
                            boxMapArray[boxIndex].put(num, boxValue + 1);
                        } else {
                            return valid;
                        }


                    }
                }
            }
            // 遍历结束 没有出现相同值 则为有效数独
            valid = true;
        }

        return valid;
    }
}
